package com.irdstudio.efp.esb.api.rest.psd.credit;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.irdstudio.basic.framework.core.constant.ESBConstant;
import com.irdstudio.basic.framework.core.constant.EsbRetCodeStandard;
import com.irdstudio.efp.esb.api.bean.psd.credit.req.RepeatApplyCheckReqBean;
import com.irdstudio.efp.esb.api.bean.psd.credit.resp.RepeatApplyCheckRespBean;
import com.irdstudio.efp.esb.api.common.EsbRespServiceBeanCreator;
import com.irdstudio.efp.esb.api.common.GroupeInterface;
import com.irdstudio.efp.esb.api.rest.EsbController;
import com.irdstudio.efp.esb.api.service.esb.EsbRespServcie;
import com.irdstudio.efp.esb.api.service.sed.SedCommonService;
import com.irdstudio.efp.esb.common.constant.EsbBizEnums;
import com.irdstudio.efp.esb.common.constant.EsbSysHeadEnums;
import com.irdstudio.efp.esb.common.constant.RespRetCode;
import com.irdstudio.efp.esb.common.server.req.EsbReqServiceBean;
import com.irdstudio.efp.esb.common.server.resp.EsbRespServiceBean;
import com.irdstudio.efp.limit.service.facade.LmtPrdContService;
import com.irdstudio.efp.limit.service.vo.LmtPrdContVO;
import com.irdstudio.efp.nls.service.facade.psd.NlsCreditApprovalInfoService;
import com.irdstudio.efp.nls.service.facade.psd.PreNlsCreditInfoService;
import com.irdstudio.efp.nls.service.facade.sx.NlsCreditInfoService;
import com.irdstudio.efp.nls.service.vo.psd.NlsCreditApprovalInfoVO;
import com.irdstudio.efp.nls.service.vo.psd.PreNlsCreditInfoVO;
import com.irdstudio.efp.nls.service.vo.sx.NlsCreditInfoVO;
import org.apache.tomcat.jni.Local;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Objects;

@RestController
@RequestMapping("/esb")
public class PsdRepeatApplyCheckController implements EsbController {

    /**
     * 日志信息
     */
    private final Logger logger = LoggerFactory.getLogger(PsdRepeatApplyCheckController.class);

    @Autowired
    private PreNlsCreditInfoService preNlsCreditInfoService;

    @Autowired
    private EsbRespServcie<RepeatApplyCheckRespBean> esbRespServcie;

    @Autowired
    private NlsCreditApprovalInfoService nlsCreditApprovalInfoService;

    @Autowired
    private NlsCreditInfoService nlsCreditInfoService;

    @Autowired
    private LmtPrdContService lmtPrdContService;


    /**
     * 重复授信申请校验
     *
     * @param esbReqServiceBean
     * @param bindingResult1
     * @param repeatApplyCheckReqBean
     * @param bindingResult2
     * @param exception
     * @return
     */
    @PostMapping("/SERVICE_30220001_16")
    public EsbRespServiceBean doRecv(@Validated @ModelAttribute("esbReqServiceBean") EsbReqServiceBean esbReqServiceBean, BindingResult bindingResult1,
                                     @Validated({GroupeInterface.psd.class}) @ModelAttribute("repeatApplyCheckReqBean") RepeatApplyCheckReqBean repeatApplyCheckReqBean, BindingResult bindingResult2, Exception exception) {
        // 设置响应对象
        RepeatApplyCheckRespBean repeatApplyCheckRespBean = new RepeatApplyCheckRespBean();
        try {
            // 参数校验
            if (Objects.nonNull(exception)) {
                //如果异常不为空，那么处理异常返回信息
                return esbRespServcie.getEsbRespServiceBeanByException(esbReqServiceBean, exception, repeatApplyCheckRespBean, EsbRetCodeStandard.JKYDCSJYBTG);
            }
            //校验失败有值：
            PreNlsCreditInfoVO preParam = new PreNlsCreditInfoVO();
            preParam.setChannelApplyNo(repeatApplyCheckReqBean.getPreVrfcLmtChanAppNo());
            PreNlsCreditInfoVO preNlsCreditInfoVO1 = preNlsCreditInfoService.queryByChannelApplyNo(preParam);
            if (Objects.isNull(preNlsCreditInfoVO1)) {
                //0 不存在预授信信息
                return esbRespServcie.getEsbRespServiceBeanByException(
                        esbReqServiceBean,new RuntimeException("不存在预授信信息"),
                        repeatApplyCheckRespBean,
                        EsbRetCodeStandard.YWLJCLYC);
            }
            if (!"02".equals(preNlsCreditInfoVO1.getStatus())) {
                //1 预授信审批状态不为通过
                return esbRespServcie.getEsbRespServiceBeanByException(
                        esbReqServiceBean,new RuntimeException("预授信审批状态不为通过"),
                        repeatApplyCheckRespBean,
                        EsbRetCodeStandard.YWLJCLYC);
            }
            //判断预授信审批时间距离现在是否已经超过了90天
            final LocalDateTime localDateTime = LocalDateTime.parse(preNlsCreditInfoVO1.getApprovalTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            if ((LocalDateTime.now().toLocalDate().toEpochDay() - localDateTime.toLocalDate().toEpochDay()) > 90) {
                repeatApplyCheckRespBean.setRetCd(EsbRetCodeStandard.YWLJCLYC.getValue());
                repeatApplyCheckRespBean.setRetMsg("预授信审批时间已经超过了90天");
                return esbRespServcie.getEsbRespServiceBeanByException(
                        esbReqServiceBean,new RuntimeException("预授信审批时间已经超过了90天"),
                        repeatApplyCheckRespBean,
                        EsbRetCodeStandard.YWLJCLYC);
            }
            //2 授信申请已经存在
            NlsCreditInfoVO nlsCreditInfoVO = nlsCreditInfoService.queryByPrdSeq(preNlsCreditInfoVO1.getApplySeq());
            if (!Objects.isNull(nlsCreditInfoVO)) {
                return esbRespServcie.getEsbRespServiceBeanByException(
                        esbReqServiceBean,new RuntimeException("授信申请已经存在"),
                        repeatApplyCheckRespBean,
                        EsbRetCodeStandard.YWLJCLYC);
            }
            return esbRespServcie.getSucessBean(esbReqServiceBean,repeatApplyCheckRespBean,EsbRetCodeStandard.SUCCESS);
        } catch (Exception ex) {
            logger.error("接口出现异常，异常信息为：", ex.getMessage());
            ex.printStackTrace();
            return esbRespServcie.getEsbRespServiceBeanByException(esbReqServiceBean, ex, repeatApplyCheckRespBean, EsbRetCodeStandard.OTHERS_EXCEPTION);
        }
    }

    @ModelAttribute("esbReqServiceBean")
    public EsbReqServiceBean getReqEsbHeadBean(HttpServletRequest request) {
        logger.info("获取 ESB请求系统头和请求应用头对象!");
        EsbReqServiceBean esbReqServiceBean = (EsbReqServiceBean) request.getAttribute("esbReqServiceBean");
        return esbReqServiceBean;
    }

    @ModelAttribute("repeatApplyCheckReqBean")
    public RepeatApplyCheckReqBean getReqEsbBodyBean(HttpServletRequest request) {
        logger.info("获取 ESB请求体！");
        String esbReqBody = (String) request.getAttribute("esbReqBody");
        return JSONObject.parseObject(esbReqBody, RepeatApplyCheckReqBean.class);
    }
}